#include "miniutil/appctrl.h"

namespace miniutil { namespace frame {

CommandQueue* CommandQueue::pinstance = NULL;

CommandQueue* CommandQueue::GetInstance()
{
    if(pinstance == NULL)
        pinstance = new CommandQueue();
    return pinstance;
}

CommandQueue::CommandQueue()
{
}

void CommandQueue::PutCommand(const std::string cmd)
{
    miniutil::auto_lock kk(&mmtx);
    vcmds.push_back(cmd);
}

std::string CommandQueue::FetchCommand()
{
    std::string out;
    miniutil::auto_lock kk(&mmtx);
    if(vcmds.size() == 0)
        return out;
    out = vcmds[0];
    vcmds.erase(vcmds.begin());
    return out;
}

//----------------------------------------------------------
int ConsoleService::WorkingTask()
{
    std::string cmd;
    std::getline(std::cin, cmd);
    if(!cmd.empty())
    CommandQueue::GetInstance()->PutCommand(cmd);
    return 0;
}

bool HttpCommandServlet::doGet(httpconnector * req)
{
	const char * h = "Content-type: text/xml\r\n\r\n";
	const char *err = "<status>Fail</status>";
	const char *ok = "<status>OK</status>";
	const char *xmlhdr = "<?xml version=\"1.0\"?>";
	req->write( h, (int)strlen(h) );

	url* purl = new url( "http://localhost/" + req->URI );
	std::string cmd = purl->getParam("command");
    if(cmd.empty())
        req->write( err, (int)strlen(err) );
    else
    {
        req->write( ok, (int)strlen(ok) );
        CommandQueue::GetInstance()->PutCommand(cmd);
    }
    return true;
}

} }
